PandaDKPMaster = LibStub("AceAddon-3.0"):NewAddon("PandaDKPMaster",
 "AceConsole-3.0", "AceEvent-3.0", "AceTimer-3.0", "AceComm-3.0",
 "LibFuBarPlugin-3.0")

local PandaDKPMasterDBver = 1.0

PandaDKPMaster.DBDefaults =
{
   ["realm"] =
   {
      dbversion = PandaDKPMasterDBver, -- Structure version of the SavedVariables DB
      DbPassword = "default", -- Password for points database broadcasting
      disenchanter = "", -- Player name of the person to give items to be disenchanted to
      bankname = "", -- Player name of the person to give items to for the guild bank
      ItemAdding = true,   -- true if items are automatically added to the database when looted
      ItemQuality = 4,
      DoNotDisturb = false,
      LootScanning = true,
      dkpforde = false, -- true if the raid gets DKP for DEd items
      dkpforbank = true,   -- true if the raid gets DKP for banked items
      KeepInSync = true, -- true -> always send our points database on a sync request
      LastSync = nil,    -- If you have not synchronized in 21 days, your entire DB is automatically thrown away and you get a fresh copy
      
      Auth =
      {
         Authorized = {},  -- a list of users that are authorized. Key is name, value is date of auth
         Failed = {},      -- a list of users that have failed authorization. Key is name, value is date
      },
      
      DKP =
      {
         Checksums = {},
         Pools = {},
         Items = {},
         Players = {},
         HistoricalDKP = {},
         Aliases = {},
         Events = {},
         Logging = {},
      },
   }
}

local AceConfig = LibStub("AceConfigDialog-3.0")
local AceReg = LibStub("AceConfigRegistry-3.0")


-- Called when the addon is first loaded.
function PandaDKPMaster:OnInitialize()
   -- Create the database
   self.db = LibStub("AceDB-3.0"):New("PandaDKPMasterDB", self.DBDefaults)
   PandaDKPMaster.db.realm.DKP.Checksums = {} -- should be moved out of saved variables
   
   -- Setup MD5
   self.MD5Lib = LibStub:GetLibrary("MDFive-1.0")
end


-- Called when the user enables the addon
function PandaDKPMaster:OnEnable()
   
   -- Enable our sub-classes
   PandaDKPMaster.Comm:Enable()
   PandaDKPMaster.Messages:Enable()
   PandaDKPMaster.Auth:Enable()
   PandaDKPMaster.Config:Enable()
   PandaDKPMaster.Pools:Enable()
   PandaDKPMaster.Items:Enable()
   PandaDKPMaster.Players:Enable()
   PandaDKPMaster.Events:Enable()
   PandaDKPMaster.Looting:Enable()
   PandaDKPMaster.Alias:Enable()
   PandaDKPMaster.Audit:Enable()
   PandaDKPMaster.Awarding:Enable()
   
   -- If our DB is older then 21 days, completely clean it out and start fresh
   --[[ if (nil == PandaDKPMaster.db.realm.LastSync
    or PandaDKPMaster.db.realm.LastSync < time() - (21 * 24 * 60 * 60)) then
      PandaDKPMaster.db.realm.DKP =
      {
         Checksums = {},
         Pools = {},
         Items = {},
         Players = {},
         HistoricalDKP = {},
         Aliases = {},
         Events = {},
         Logging = {},
      }
      PandaDKPMaster:Print("WARNING! Your database was more then 21 days old and needs to be refreshed! You can refresh it from the main interface screen.");
   else
   ]]
      -- Clear out old events, summarizing when necessary
      PandaDKPMaster.Events:SummarizeEvents(PandaDKPMaster:GetDatestamp(PandaDKPMaster:ThirtyDaysAgo()))
   --end
   
   -- Do the startup stuff 30 seconds after login
   PandaDKPMaster:ScheduleTimer(function() PandaDKPMaster:OnStartup() end, 30)
   
   -- Set up the FuBar plugin
	local optionsTable = {
		name = "PandaDKPMaster",
		desc = self.notes,
		handler = PandaDKPMaster,
		type = 'group',
		args = {}
	}
 	PandaDKPMaster.OnMenuRequest = optionsTable
end


function PandaDKPMaster:OnStartup()

   -- Make sure we're in Panda Attack
   local guildName, guildRankName, guildRankIndex = GetGuildInfo("player")
   if ("Panda Attack" ~= guildName) then
      PandaDKPMaster:Print("This character is not in Panda Attack")
      return
   end
   
   -- Authenticate ourselves
   PandaDKPMaster.Auth:HandleReauth()
   
   -- Start processing the message queue
   PandaDKPMaster.Messages:StartTimer()
   
   -- If we're IT, send the message
   if (not PandaDKPMaster.db.realm.DoNotDisturb) then
      PandaDKPMaster.Comm:SendClient("GUILD", "IT")
   end
   
   -- SYNC with other people every hour. Also start a SYNC right now
   PandaDKPMaster:ScheduleRepeatingTimer(function() PandaDKPMaster.Sync:SendSyncRequest() end, 60 * 60)
   PandaDKPMaster.Sync:SendSyncRequest()
   
end


-- Called when the user enables the addon
function PandaDKPMaster:OnDisable()
   -- Stop processing the message queue
   PandaDKPMaster.Messages:StopTimer()
end



function PandaDKPMaster:RecalculateAllDKP()
   
   for player, data in pairs(PandaDKPMaster.db.realm.DKP.Players) do
      for pool, dkp in pairs(data.Pools) do
         data.Pools[pool] = 0.0
      end
   end
   
   for player, pools in pairs(PandaDKPMaster.db.realm.DKP.HistoricalDKP) do
      for pool, dkp in pairs(pools) do
         dkp = tonumber(string.format("%.2f", dkp))
         PandaDKPMaster.Players:AddDKP(player, dkp, pool)
      end
   end
   
   for md5, event in pairs(PandaDKPMaster.db.realm.DKP.Events) do
      if ("PI" == event.type) then
         local dkp = tonumber(string.format("%.2f", event.dkp))
         PandaDKPMaster.Players:AddDKP(event.player, dkp * -1, event.pool)
      elseif ("AW" == event.type) then
         local dkp = tonumber(string.format("%.2f", event.dkp))
         for i, player in pairs(event.players) do
         PandaDKPMaster.Players:AddDKP(player, dkp, event.pool)
         end
      end
   end
   
   PandaDKPMaster.Sync:ResetChecksum("DKP", nil)
   
   -- Update the class for each player
	local numGuildMembers = GetNumGuildMembers(true)
	local name, rank, rankIndex, level, class, zone, note, officernote, online, status, classconst
	for i = 1, numGuildMembers, 1 do
		name, rank, rankIndex, level, class, zone, note, officernote, online, status, classconst = GetGuildRosterInfo(i)
		if (nil ~= PandaDKPMaster.db.realm.DKP.Players[name]) then
		   PandaDKPMaster.db.realm.DKP.Players[name].Class = class
		end
   end
end
